const reg =
  /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/;

// src 属性
async function srcEle(page, { selector, url }) {
  const srcs = await page.$$eval(selector, (el) =>
    el.map((x) => x.getAttribute("src"))
  );

  return srcs
    .filter((v) => reg.test(v))
    .map((v) => {
      let next = v.indexOf("https://") !== -1 || v.indexOf("http://") !== -1;
      return next ? v : new URL(url).origin + "/" + v;
    });
}

// href 属性
async function hrefEle(page, { selector }) {
  const hrefs = await page.$$eval(selector, (el) =>
    el.map((x) => x.getAttribute("href"))
  );

  return hrefs;
}

// text
async function textEle(page, { selector }) {
  const list = await page.$$eval(selector, (e) => {
    return e.map((x) => x.innerText);
  });

  return list;
}

const elementMap = {
  src: srcEle,
  text: textEle,
  href: hrefEle,
};

module.exports = async (page, { type, selector, url }) => {
  await page.waitForSelector(selector);
  return elementMap[type] && elementMap[type](page, { selector, url });
};
